<?php
declare(strict_types=1);

namespace App\AdminApi\Modular\Administer\Search;

use Core\Basics\BasicsSearch;
use App\Common\Modular\Administer\Model\LogModel;
use Core\Package\Export\Excel;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Collection;
use Hyperf\Database\Model\Relations\HasOne;
use Zms\Unit\Is;
use App\Common\Query\Query;

class LogSearch extends BasicsSearch
{

    public function query(): Builder
    {
        return LogModel::query()
            ->when(isset($this->where['name']) && Is::notEmpty($this->where['name']), function (Builder $query) {
                Query::LikeSearch($query, 'name', $this->where['name']);
            })
            ->when(isset($this->where['url']) && Is::notEmpty($this->where['url']), function (Builder $query) {
                Query::LikeSearch($query, 'url', $this->where['url']);
            })
            ->when(isset($this->where['user_id']) && Is::notEmpty($this->where['user_id']), function (Builder $query) {
                Query::EqualOrInSearch($query,'user_id',$this->where['user_id']);
            })
            ->when(isset($this->where['os']) && Is::notEmpty($this->where['os']), function (Builder $query) {
                $query->where(['os' => $this->where['os']]);
            })
            ->when(isset($this->where['ip']) && Is::notEmpty($this->where['ip']), function (Builder $query) {
                Query::IpSearch($query, 'ip', $this->where['ip']);
            })
            ->when(isset($this->where['time']) && Is::notEmpty($this->where['time']), function (Builder $query) {
                Query::TimeRangeSearch($query, '`time`', $this->where['time']);
            })
            ->with(['user' => function (HasOne $hasOne) {
                $hasOne->select(['id', 'nickname', 'avatar']);
            }])
            ->orderByRaw($this->order);
    }


    public function export(string $filename): array
    {
        $ExportData = [];
        $this->query()->chunk(200, function (Collection $users) use (&$ExportData) {
            foreach ($users->toArray() as $item) {
                $ExportData[] = [
                    $item['name'],
                    "[{$item['method']}]:{$item['url']}",
                    $item['ip'],
                    $item['guard'],
                    $item['app'],
                    date("Y-m-d H:i:s", $item['time']),
                    $item['status'] ? '成功' : '失败',
                    $item['browser'],
                    $item['user']['nickname'] ?? '',
                ];
            }
        });
        return Excel::export($filename, ['行为', '请求地址', '操作IP', '用户组', '应用标识', '时间', '状态', '浏览器', '操作人'], $ExportData);
    }

}